package com.derbysoft.lowcostadapter.webservice.impl;

import com.derbysoft.lowcostadapter.commons.exception.LCBInvocationException;
import com.derbysoft.lowcostadapter.commons.log.Direction;
import com.derbysoft.lowcostadapter.commons.log.LogDetailPair;
import com.derbysoft.lowcostadapter.commons.log.TransactionLogger;
import com.derbysoft.lowcostadapter.commons.utils.ErrorMessageUtils;
import com.derbysoft.lowcostadapter.webservice.LowCostWebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.ws.client.core.WebServiceTemplate;

import java.util.HashSet;
import java.util.Set;

@Component("reservationWebService")
public class ReservationWebServiceImpl implements LowCostWebService {

    @Autowired
    @Qualifier("bookWebServiceTemplate")
    protected WebServiceTemplate webServiceTemplate;

    @Override
    public Object send(Object rq) throws LCBInvocationException {
        Set<LogDetailPair> logDetails = TransactionLogger.getLogDetails().get();
        if (logDetails == null) {
            logDetails = new HashSet<LogDetailPair>();
            TransactionLogger.getLogDetails().set(logDetails);
        }
        logDetails.add(LogDetailPair.build(rq, Direction.TO_HOTEL));
        try {
            Object response = webServiceTemplate.marshalSendAndReceive(rq);
            logDetails.add(LogDetailPair.build(response, Direction.FROM_HOTEL));
            return response;
        } catch (Exception e) {
            TransactionLogger.getReservationLogger().get().setError(true);
            logDetails.add(LogDetailPair.build(ErrorMessageUtils.buildErrorMessage(e), Direction.FROM_HOTEL));
            throw new LCBInvocationException(e.getMessage(), e);
        }
    }

    public void setWebServiceTemplate(WebServiceTemplate webServiceTemplate) {
        this.webServiceTemplate = webServiceTemplate;
    }
}
